package com.mrdeer.uaa.common;

import com.mrdeer.common.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：xie jianchu
 * @date ：Created in 2020/9/4 0004 16:45
 */
public class WebUtils {

    public static final String UTF_8 = "UTF-8";

    private static final String VERSION = "1.0.0";

    private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();

    public static void setIp(String ip) {
        ipThreadLocal.set(ip);
    }

    public static String getIp() {
        return ipThreadLocal.get();
    }

    private WebUtils() {

    }

    public static String retrieveClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (isUnavailableIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isUnavailableIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isUnavailableIp(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static boolean isUnavailableIp(String ip) {
        return StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
    }
}
